package com.baiku.sanhos.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.baiku.sanhos.config.WebSocket;
import com.baiku.sanhos.mapper.DrugMapper;
import com.baiku.sanhos.mapper.RecipeMapper;
import com.baiku.sanhos.mapper.RecordMapper;
import com.baiku.sanhos.pojo.entity.*;
import com.baiku.sanhos.pojo.vo.DoctorIndexVo;
import com.baiku.sanhos.pojo.vo.RecipeVo;
import com.baiku.sanhos.pojo.vo.UserInventoryVO;
import com.baiku.sanhos.response.ResultVO;
import com.baiku.sanhos.response.StatusCode;
import com.baiku.sanhos.utils.model.SanhosDataModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
@RequestMapping("/pa/recipe")
public class RecipeController {

    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private RecipeMapper recipeMapper;

    @Autowired
    private DrugMapper drugMapper;

    /**
     * 管理员批量删除就诊记录的消息
     * @param ids
     * @return
     */
    @DeleteMapping("/deleteByIds")
    public ResultVO deleteByIds(@RequestBody List<Integer> ids){
        recordMapper.deleteByIds(ids);
        return ResultVO.ok();
    }

    /**
     * 管理员查询就诊记录模块
     * @param record
     * @return
     */
    @PostMapping("/selectAdminAll")
    public ResultVO selectAdminAll(@RequestBody Record record) {
        int pageSize = record.getPageSize();
        int page = record.getPage();
        Map<String, Object> map = new HashMap<>();
        int total = recordMapper.getTotalAllBooking(record.getNickName());//总条数
        int totalPages = (int) Math.ceil((double) total / pageSize);//计算总页数
        List<Record> recordList;
        if (totalPages == 0) {
            recordList = new ArrayList<>();
        } else {
            int offset = (page - 1) * pageSize;
            recordList = recordMapper.selectAdminAll(pageSize, offset, record.getNickName(),record.getDoctorName());
        }
        map.put("record", recordList);
        map.put("total", total);
        return ResultVO.ok(map);
    }

    @PostMapping("/selectAll")
    public ResultVO selectAll(@RequestBody Record record) {
        int pageSize = record.getPageSize();
        int page = record.getPage();
        Map<String, Object> map = new HashMap<>();
        int total = recordMapper.getTotalBooking(record.getNickName(), record.getDoctorNo());//总条数
        int totalPages = (int) Math.ceil((double) total / pageSize);//计算总页数
        List<Record> recordList;
        if (totalPages == 0) {
            recordList = new ArrayList<>();
        } else {
            int offset = (page - 1) * pageSize;
            recordList = recordMapper.selectAll(pageSize, offset, record.getNickName(), record.getDoctorNo());
        }
        map.put("record", recordList);
        map.put("total", total);
        return ResultVO.ok(map);
    }

    @DeleteMapping("/deleteById/{id}")
    public ResultVO deleteById(@PathVariable Integer id) {
        recordMapper.deleteById(id);
        return ResultVO.ok();
    }

    /**
     * 管理员删除已交费的处方信息
     * @param id
     * @return
     */
    @DeleteMapping("/deleteAdminRecipeById/{id}")
    public ResultVO deleteAdminRecpiceById(@PathVariable Integer id) {
        recipeMapper.deleteAdminRecipeById(id);
        return ResultVO.ok();
    }
    @PostMapping("/addRecipe")
    public ResultVO addRecipe(@RequestBody RecipeVo recipeVo) {
        recipeMapper.addRecipe(recipeVo);
        return ResultVO.ok();
    }

    @PostMapping("/selectRecipeAll")
    @PreAuthorize("hasAuthority('DDD')")
    public ResultVO selectRecipeAll(@RequestBody RecipeVo recipeVo) {
        int pageSize = recipeVo.getPageSize();
        int page = recipeVo.getPage();
        Map<String, Object> map = new HashMap<>();
        int total = recipeMapper.getTotalBooking(recipeVo.getNickName(), recipeVo.getDoctorNo());//总条数
        int totalPages = (int) Math.ceil((double) total / pageSize);//计算总页数
        List<RecipeVo> recipeVoList;
        if (totalPages == 0) {
            recipeVoList = new ArrayList<>();
        } else {
            int offset = (page - 1) * pageSize;
            recipeVoList = recipeMapper.selectAll(pageSize, offset, recipeVo.getNickName(), recipeVo.getDoctorNo());
        }
        map.put("recipe", recipeVoList);
        map.put("total", total);
        return ResultVO.ok(map);
    }

    /**
     * 管理员全查处方信息
     * @param recipeVo
     * @return
     */
    @PostMapping("/selectAdminRecipeAll")
    public ResultVO selectAdminRecipeAll(@RequestBody RecipeVo recipeVo) {
        int pageSize = recipeVo.getPageSize();
        int page = recipeVo.getPage();
        Map<String, Object> map = new HashMap<>();
        int total = recipeMapper.getAdminTotalBooking(recipeVo.getNickName());//总条数
        int totalPages = (int) Math.ceil((double) total / pageSize);//计算总页数
        List<RecipeVo> recipeVoList;
        if (totalPages == 0) {
            recipeVoList = new ArrayList<>();
        } else {
            int offset = (page - 1) * pageSize;
            recipeVoList = recipeMapper.selectAdminAll(pageSize, offset, recipeVo.getNickName());
        }
        map.put("recipe", recipeVoList);
        map.put("total", total);
        return ResultVO.ok(map);
    }
    @Autowired
    private WebSocket webSocket;	// 导入刚刚写好的 WebSocket 工具类
    // 支付宝网关：沙箱环境 (真实环境的话改外：https://openapi.alipay.com/gateway.do)
    private static final String URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    // APPID (请自行填写，真实环境请做对应修改)
    private static final String APP_ID = "9021000123605479";
    // 应用私钥 (请自行填写，真实环境请做对应修改)
    private static final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCQ9fHd8BNlroDOKXz8KULP/oeZozt9xgb3aUNH8zEkGDbZBQvKA8/5zD4D3g7TL/QGUiKSdROL+VNCNL5ihirtppUbVWggyA/s/AMVnq0udI7i7KjsrOCFGddFzi+sNvPAzrhs/U6rcsEGz5cx9RFd24cOdLUp7aLTlmX3L08/Ye7xWdS1k6VL7GCW5/7zdbDAfxpj9cE53jwS+zGoKUrBwSPJKBYxsnPFTmU4tPyOs9aHtCdixqlKlqY8sEv3awOCLEUXtaXtNjySLBVbBFCa0RjBLiGpIM2j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DhOPYyVYdTRsctUYGYTJVKvDFbHN1QpQA646MwFCtbtQdAoGBALpsbs5qvdfB/wTeWXbRyForemT6dsyaJ8wlhOWfTZTG6YwM3ELk0iN5/POSX5qlv/HrdMdAjtBS7n4LoMXRLVnBCtUtYSJ9eFxfiGfdCE/126HtSJW8hFYtx7ZKFLe63flfQrmHsj48YTJ+PUqMMx5GN00pnVcow1eGsUQAPHca";
    // 数据返回的格式 (只支持json格式)
    private static final String FORMAT = "json";
    // 验签编码 (根据需要修改)
    private static final String CHARSET = "UTF-8";
    // 支付宝公钥 (请自行填写，真实环境请做对应修改)
    private static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo9S4/3V8gtf19sxx+7PWdesn4PQvr9uAHntjmlfV3v5uVBsU7CtmKzy1A9XJCZD4OVFHWS2T+dR3TbR9qm39wgKaT3DJHdCvP96fQ2h3EKEd/0ox+nTo8HX67dmIje+BUT9rDmrSTdG1TTRCsZMRLj5XysesjKk2Z7z/pbKKbJfSNr5DYyVDyUpz3gafWKd+SrItEU53L0Qyi3f8v9xAe+6ttRG4lQDfKMI6hVFU3meK/kcd0x5eBdxYGjkKJOSOD1EVPRVw8HRM4WDXaux0lRFaM+i+oSLYXBLcilArPwMmQXLPA5+y4eXz+YruOsgFfu1T3A5yDoxe+5Y9GAIVawIDAQAB";
    // 验签加密方法 (根据需要修改)
    private static final String SIGN_TYPE = "RSA2";

    @Autowired
    RecipeMapper recipe;
    @Autowired
    SanhosDataModel sanhosDataModel;
    @PostMapping("/sandboxPay/{id}/{doctorNo}/{outTradeNo}")
    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    @ApiOperation("清单打印")
    public ResultVO sandboxPay(@PathVariable Integer id ,@PathVariable String doctorNo,@PathVariable String outTradeNo) throws AlipayApiException {
        RecipeVo recipeVo = recipe.queryByIdFindrecordId(id);
        if(recipeVo.getStatus()==1){
            return ResultVO.ok(StatusCode.PAYMENT_ERROR);
        }else if(recipeVo.getTotalmoney()==0){
            return ResultVO.ok(StatusCode.DISPENSING_ERROR);
        }
        UserInventoryVO inventory = recipe.userInventory(recipeVo.getRecordId());
        // 使用支付宝沙箱数据生成支付宝支付二维码
        String alipayQrCode = generateAlipayQrCode(id,doctorNo,outTradeNo);
        inventory.setAlipayQrCode(alipayQrCode);
        return  sanhosDataModel.printInventory(inventory);
    }

   public String generateAlipayQrCode(Integer id,String doctorNo,String outTradeNo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
       request.setNotifyUrl("http://xhe96g.natappfree.cc/pa/recipe/call");
        /*String currenTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String orderNumber = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = currenTime + orderNumber;*/
        RecipeVo recipeVo = recipeMapper.selectRecipeById(id, doctorNo);
        model.setOutTradeNo(outTradeNo);
        String totalMoney = String.valueOf(recipeVo.getTotalmoney());
        model.setTotalAmount(totalMoney);
        model.setSubject("订单标题");
        // 设置其他参数...

        request.setBizModel(model);
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            return response.getQrCode();// 获取支付宝生成的二维码内容
        } else {
            throw new RuntimeException("支付宝接口调用失败");
        }
    }

    @ApiOperation(value = "支付宝支付 异步通知")
    @PostMapping("/call")
    public void call(HttpServletRequest request, HttpServletResponse response, AliReturnPay aliReturnPay) throws IOException {
        // 通知返回的数据会封装到 AliReturnPay 类中
        response.setContentType("type=text/html;charset=UTF-8");
        String orderNo = aliReturnPay.getOut_trade_no(); // 获得订单号，对数据进行修改
        OpenDrug openDrug = drugMapper.queryByOrderNo(orderNo);
        // 支付成功的返回码
        if (("TRADE_SUCCESS").equals(aliReturnPay.getTrade_status())){
            // 向前端发送一条支付成功的通知
            recipeMapper.updateByIdStatus(openDrug.getRecipeId());
            webSocket.sendMessage("true");
        }
    }

    /**
     * 管理员查看患者配药
     * @param page
     * @param pageSize
     * @param recipeId
     * @return
     */
    @GetMapping("/selectAdminOpenDrug")
    public ResultVO selectAdminOpenDrug(@RequestParam("page") int page,
                                   @RequestParam("pageSize") int pageSize,
                                   @RequestParam("id") int recipeId){
        RecipeVo recipeVo = recipeMapper.queryById(recipeId);
        Map<String, Object> map = new HashMap<>();
        int total = recipeMapper.getTotalOpenDrug(recipeId,recipeVo.getSchedulTime(),recipeVo.getNickName());//总条数
        int totalPages = (int) Math.ceil((double) total / pageSize);//计算总页数
        List<OpenDrug> openDrugs;
        if (totalPages == 0) {
            openDrugs = new ArrayList<>();
        } else {
            int offset = (page - 1) * pageSize;
            openDrugs = recipeMapper.selectOpenAll(pageSize, offset,recipeId,recipeVo.getSchedulTime(),recipeVo.getNickName());
        }
        map.put("openDrugs", openDrugs);
        map.put("total", total);
        return ResultVO.ok(map);
    }

    @GetMapping("/selectOpenDrug")
    @PreAuthorize("hasAuthority('DDD')")
    public ResultVO selectOpenDrug(@RequestParam("page") int page,
                                   @RequestParam("pageSize") int pageSize,
                                   @RequestParam("id") int recipeId){
        RecipeVo recipeVo = recipeMapper.queryById(recipeId);
        Map<String, Object> map = new HashMap<>();
        int total = recipeMapper.getTotalOpenDrug(recipeId,recipeVo.getSchedulTime(),recipeVo.getNickName());//总条数
        int totalPages = (int) Math.ceil((double) total / pageSize);//计算总页数
        List<OpenDrug> openDrugs;
        if (totalPages == 0) {
            openDrugs = new ArrayList<>();
        } else {
            int offset = (page - 1) * pageSize;
            openDrugs = recipeMapper.selectOpenAll(pageSize, offset,recipeId,recipeVo.getSchedulTime(),recipeVo.getNickName());
        }

        map.put("openDrugs", openDrugs);
        map.put("status",recipeVo.getStatus());
        map.put("total", total);
        return ResultVO.ok(map);
    }

    @PostMapping("/addOpenDrug")
    @PreAuthorize("hasAuthority('DDD')")
    public ResultVO addOpenDrug(@RequestBody OpenDrug openDrug){
        Drug drug = drugMapper.queryByDrugName(openDrug.getDrugName());
        RecipeVo recipeVo = recipeMapper.selectByIdFindTime(openDrug.getRecipeId());
        openDrug.setDrugNo(drug.getDrugNo());
        openDrug.setUnitprice(drug.getUnitprice());
        openDrug.setUnit(drug.getUnit());
        openDrug.setNickName(recipeVo.getNickName());
        openDrug.setSchedulTime(recipeVo.getSchedulTime());
        String currenTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String orderNumber = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = currenTime + orderNumber;
        openDrug.setOutTradeNo(out_trade_no);
        int num = drugMapper.insertOpenDrug(openDrug);
        if(num>0){
            double money = openDrug.getNumber()*drug.getUnitprice()+recipeVo.getTotalmoney();//给患者添加药品成功,算出总金额
            recipeMapper.uodateByIdMoney(openDrug.getRecipeId(),money);
            Integer inventory = drug.getInventory()-openDrug.getNumber();
            drugMapper.updateByDrugName(openDrug.getDrugName(),inventory);//根据药品名称去减库存
            return ResultVO.ok(out_trade_no);
        }
        return ResultVO.ok();
    }

    @DeleteMapping("/deleteByIdOpenDrug/{id}")
    @PreAuthorize("hasAuthority('DDD')")
    public ResultVO deleteByIdOpenDrug(@PathVariable Integer id){
        OpenDrug openDrug= drugMapper.selectByIdFindMoney(id);//开出药品的价格
        RecipeVo recipeVo = drugMapper.selectByIdFindTotalMoney(id);//获取总价格
        double money = recipeVo.getTotalmoney()- openDrug.getUnitprice()*openDrug.getNumber();
        int num = drugMapper.updateByIdOpenDrug(openDrug.getRecipeId(),money);
        if(num>0){
            drugMapper.deleteByIdOpenDrug(id);
            Drug drug = drugMapper.queryByDrugName(openDrug.getDrugName());//根据药品名称去查该药品的库存
            Integer inventory = drug.getInventory()+openDrug.getNumber();//总库存加上删除的库存
            drugMapper.updateByDrugName(openDrug.getDrugName(),inventory);//根据药品名称修改该药品的库存
            return ResultVO.ok();
        }
        return ResultVO.ok();
    }

    @PostMapping("/updateByIdOpenDrug")
    @PreAuthorize("hasAuthority('DDD')")
    public ResultVO updateByIdOpenDrug(@RequestBody OpenDrug openDrug){
        OpenDrug OriginalData = drugMapper.selectByIdFindNumber(openDrug.getId());//原来的数量
        Drug drug = drugMapper.queryByDrugName(OriginalData.getDrugName());//根据药品名称去查该药品的库存
        int num = drugMapper.updateByIdNumber(openDrug.getId(),openDrug.getNumber());
        if(num>0){
            Integer number;
            openDrug = drugMapper.selectByIdFindNumber(openDrug.getId());//修改后的数量
            if(OriginalData.getNumber()<openDrug.getNumber()){//原来的数量少于修改后的，增加总金额
                 number = openDrug.getNumber()-OriginalData.getNumber();
            }else {//原来的数量大于修改后的，减少总金额
                number = openDrug.getNumber()-OriginalData.getNumber();
            }
            double money = OriginalData.getUnitprice()*number;
            RecipeVo recipeVo = recipeMapper.selectByIdFindTotalMoney(openDrug.getId());
            double totalMoney = money + recipeVo.getTotalmoney();
            drugMapper.updateByIdMoney(openDrug.getRecipeId(),totalMoney);//修改开的药品的总金额
            Integer inventory = drug.getInventory()-(openDrug.getNumber()-OriginalData.getNumber());//总数量减去原来增加的数量再减去修改后的数量
            drugMapper.updateByDrugName(openDrug.getDrugName(),inventory);
            return ResultVO.ok();
        }
        return ResultVO.ok();
    }

    /*private final String APP_ID = "9021000123605479";
    private final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCXNw2WmqyKCGYB3kOndSOC0Mr52uhkApfWKyTUy+66BwSosory2qZCLAc+0x/hEuZi1LIqjNzTz6whp7AYriCYYAj8Bjb8qJF64Zw7iiXR0zSVwk8rU4EugP4oXFsfLuPV4XJ+38AfyR2TonwNrvLdBocy8V4kiaogdaXBdurCBgSpWwvaB9aeF+QJk+j0+g3V25b5hrjG3ViNjfquJEf0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9H1xeZibCZo3HT0SyRUqRtVWYPBUJO79kr9pLCNXacu2klHaZ77GLQWRegDjULKEkF43mzmHfR7ga27FfhECgYAP/9tyeiX228rxzv7dCg6S6UeUhJVL/Dr/3PMKqB1u1z3WVlHxF9PjdQJ6OCbsLizXBnmAxlDUPkLi1ADeYyk0m9IiBXni5RrYQ1h26hUPDA109BTrYcKbnWijs+cR2ykZDNYlhcC5PEjiBTkrs7pB6V39JG/7jh5VKINRzQkS9Q==";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo9S4/3V8gtf19sxx+7PWdesn4PQvr9uAHntjmlfV3v5uVBsU7CtmKzy1A9XJCZD4OVFHWS2T+dR3TbR9qm39wgKaT3DJHdCvP96fQ2h3EKEd/0ox+nTo8HX67dmIje+BUT9rDmrSTdG1TTRCsZMRLj5XysesjKk2Z7z/pbKKbJfSNr5DYyVDyUpz3gafWKd+SrItEU53L0Qyi3f8v9xAe+6ttRG4lQDfKMI6hVFU3meK/kcd0x5eBdxYGjkKJOSOD1EVPRVw8HRM4WDXaux0lRFaM+i+oSLYXBLcilArPwMmQXLPA5+y4eXz+YruOsgFfu1T3A5yDoxe+5Y9GAIVawIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String CHARSET = "UTF-8";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://7njihn.natappfree.cc/pa/recipe/returnUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/pa/recipe/returnUrl";
    @RequestMapping("/alipay/{id}")
    public ResultVO alipay(@PathVariable Integer id, HttpServletResponse httpResponse) throws IOException {
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);
        //根据订单编号,查询订单相关信息
        //Order order = IPayService.selectById(orderId);
        //UUID生成订单号
        String currenTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String orderNumber = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = currenTime + orderNumber;
        //付款金额，必填
        String total_amount = "0.01";
        //订单名称，必填
        String subject = "订单测试";
        //商品描述，可空
        String body = "";
        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        //httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        System.out.println(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        return ResultVO.ok(form);
    }

    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号=" + out_trade_no);
            System.out.println("支付宝交易号=" + trade_no);
            System.out.println("付款金额=" + total_amount);

            //支付成功，修复支付状态
            // payService.updateById(Integer.valueOf(out_trade_no));
            return "ok";//跳转付款成功页面
        } else {
            return "no";//跳转付款失败页面
        }
    }*/
   /* @GetMapping("/alipay/{id}")
    public ResponseEntity<byte[]> Payment(@PathVariable Integer id) {
        int width = 200;
        int height = 200;
        String format = "png";

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        String paymentUrl = "";
        String text = paymentUrl;
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            BufferedImage qrcodeImage = toBufferedImage(bitMatrix);
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Payment");

            // 将二维码图像插入到Excel表中的适当位置
            int qrcodeColumnIndex = 0;
            int qrcodeRowIndex = 0;
            insertImageIntoCell(sheet, qrcodeImage, qrcodeColumnIndex, qrcodeRowIndex, format);

            // 将Excel文件转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();

            // 设置响应头信息，指定响应内容为Excel文件类型和下载文件的名称
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "payment.xlsx");

            // 将生成的Excel文件的字节数组作为响应体返回给前端
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(outputStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void insertImageIntoCell(Sheet sheet, BufferedImage image, int columnIndex, int rowIndex, String format) throws IOException {
        Drawing<?> drawing = sheet.createDrawingPatriarch();
        XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, columnIndex, rowIndex, columnIndex + 1, rowIndex + 1);
        anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);

        byte[] imageData = convertImageToByteArray(image, format);
        int pictureIndex = sheet.getWorkbook().addPicture(imageData, Workbook.PICTURE_TYPE_PNG);
        XSSFDrawing xssfDrawing = (XSSFDrawing) drawing;
        XSSFPicture picture = xssfDrawing.createPicture(anchor, pictureIndex);
        picture.resize();
    }

    private byte[] convertImageToByteArray(BufferedImage image, String format) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, format, baos);
        return baos.toByteArray();
    }

    private BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }*/


    /**
     * 根据用户账号查看就诊记录
     * @param username 账号
     * @return 就诊记录数据
     */
    @ApiOperation("根据用户账号获取就诊记录数据")
    @GetMapping("/listUserRecipeData/{username}")
    @PreAuthorize("hasAnyAuthority('Details')")
    public ResultVO ListUserRecipeData(@PathVariable String username){
        return ResultVO.ok(recipeMapper.listUserInventory(username));
    }
}

